package com.example.sunmiv1.activity;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.CreditOrderAdapter;
import com.example.sunmiv1.base.BaseActivity;
import com.example.sunmiv1.entity.CreditOrderListInfo;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CreditOrderActivity extends BaseActivity {


    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.creditOrder_creditView)
    View creditOrderCreditView;
    @BindView(R.id.creditOrder_creditLayout)
    RelativeLayout creditOrderCreditLayout;
    @BindView(R.id.creditOrder_repaymentView)
    View creditOrderRepaymentView;
    @BindView(R.id.creditOrder_repaymentLayout)
    RelativeLayout creditOrderRepaymentLayout;
    @BindView(R.id.creditOrder_startTime)
    TextView creditOrderStartTime;
    @BindView(R.id.creditOrder_endTime)
    TextView creditOrderEndTime;
    @BindView(R.id.creditOrder_edit)
    EditText creditOrderEdit;
    @BindView(R.id.creditOrder_search)
    ImageView creditOrderSearch;
    @BindView(R.id.creditOrder_listView)
    PullToRefreshListView creditOrderListView;
    @BindView(R.id.creditOrder_creditViewTv)
    TextView creditOrderCreditViewTv;
    @BindView(R.id.creditOrder_repaymentViewTv)
    TextView creditOrderRepaymentViewTv;

    private int page = 1;
    private CreditOrderListInfo listInfo;
    private List<CreditOrderListInfo.DataBean.ListBean> list = new ArrayList<>();
    private LoadingDialog loadingDialog;
    private int screenType = 2;
    private CreditOrderAdapter creditOrderAdapter;
    private Context context;
    private ACache aCache;
    private String startTime = "", endTime = "";

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    list.addAll(listInfo.getData().getList());
                    setCreditOrderAdapter();
                    break;
                case 2:
                    break;
            }
        }
    };

    @Override
    protected void initView() {
        setContentView(R.layout.activity_credit_order);
        ButterKnife.bind(this);
        titleTitle.setText(R.string.creditOrderTitle);
        context = this;
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(this);
    }

    @Override
    protected void initData() {
        setCreditOrderAdapter();
        getUserArrearage();
    }

    @Override
    protected void initListener() {
        creditOrderListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                list.clear();
                setCreditOrderAdapter();
                if (screenType == 2) {
                    getUserArrearage();
                } else {
                    getRepayRecord();
                }
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                if (screenType == 2) {
                    getUserArrearage();
                } else {
                    getRepayRecord();
                }
            }
        });
        creditOrderEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(creditOrderEdit.getText().toString().trim())) {
                    page = 1;
                    list.clear();
                    setCreditOrderAdapter();
                    if (screenType == 2) {
                        getUserArrearage();
                    } else {
                        getRepayRecord();
                    }
                }
            }
        });
    }


    @OnClick({R.id.title_back, R.id.creditOrder_creditLayout, R.id.creditOrder_repaymentLayout, R.id.creditOrder_startTime, R.id.creditOrder_endTime, R.id.creditOrder_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.creditOrder_creditLayout:
                creditOrderStartTime.setText("");
                startTime = "";
                creditOrderCreditView.setVisibility(View.VISIBLE);
                creditOrderRepaymentView.setVisibility(View.GONE);
                creditOrderCreditViewTv.setTextColor(getResources().getColorStateList(R.color.text_333));
                creditOrderRepaymentViewTv.setTextColor(getResources().getColorStateList(R.color.text_999));
                page = 1;
                list.clear();
                screenType = 2;
                creditOrderAdapter.setScreenType(screenType);
                setCreditOrderAdapter();
                getUserArrearage();
                break;
            case R.id.creditOrder_repaymentLayout:
                creditOrderStartTime.setText("");
                startTime = "";
                creditOrderCreditView.setVisibility(View.GONE);
                creditOrderRepaymentView.setVisibility(View.VISIBLE);
                creditOrderCreditViewTv.setTextColor(getResources().getColorStateList(R.color.text_999));
                creditOrderRepaymentViewTv.setTextColor(getResources().getColorStateList(R.color.text_333));
                page = 1;
                list.clear();
                screenType = 1;
                creditOrderAdapter.setScreenType(screenType);
                setCreditOrderAdapter();
                getRepayRecord();
                break;
            case R.id.creditOrder_startTime:
                creditOrderStartTime.setText("");
                startTime = "";
                Tools.getDateFromDatePickerDialog(creditOrderStartTime, time -> {
                    startTime = time + " 00:00:00";
                });
                break;
            case R.id.creditOrder_endTime:
                creditOrderEndTime.setText("");
                endTime = "";
                Tools.getDateFromDatePickerDialog(creditOrderEndTime, time -> {
                    endTime = time + " 23:59:59";
                });
                break;
            case R.id.creditOrder_search:
                page = 1;
                list.clear();
                setCreditOrderAdapter();
                if (screenType == 2) {
                    getUserArrearage();
                } else {
                    getRepayRecord();
                }
                break;
        }
    }

    private void setCreditOrderAdapter() {
        if (creditOrderAdapter == null) {
            creditOrderAdapter = new CreditOrderAdapter(list);
            creditOrderListView.setAdapter(creditOrderAdapter);
        } else {
            creditOrderAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 獲取用戶賒賬記錄
     */
    private void getUserArrearage() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("credit_id", "");
            jsonObject.put("page", page);
            jsonObject.put("limit", "20");
            if ("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("editor_type", "1");
            } else {
                jsonObject.put("editor_type", "2");
            }
            jsonObject.put("order_no", "");
            jsonObject.put("start_time", startTime);
            jsonObject.put("end_time", endTime);
            jsonObject.put("state", "");//還款狀態 1已還清 2未還清
            jsonObject.put("searchText", creditOrderEdit.getText().toString().trim());//用戶暱稱、姓名、手機號(搜索)
            jsonObject = Tools.createParameterCode(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(context, Common.GET_USER_ARREARAGE, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                loadingDialog.dismiss();
                creditOrderListView.onRefreshComplete();
                try {
                    JSONObject json = new JSONObject(text);
                    Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (json.getInt("status") == 1) {
                        listInfo = GsonUtils.JsonToBean(text, CreditOrderListInfo.class);
                        Message msg = new Message();
                        msg.what = 1;
                        handler.sendMessage(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
                creditOrderListView.onRefreshComplete();
            }
        });
    }


    /**
     * 獲取還款記錄
     */
    private void getRepayRecord() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("credit_id", "");
            jsonObject.put("page", page);
            jsonObject.put("limit", "20");
            jsonObject.put("order_no", "");
            jsonObject.put("start_time", startTime);
            jsonObject.put("end_time", endTime);
            jsonObject.put("searchText", creditOrderEdit.getText().toString().trim());
            jsonObject = Tools.createParameterCode(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(context, Common.GET_REPAY_RECORD, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                loadingDialog.dismiss();
                creditOrderListView.onRefreshComplete();
                try {
                    JSONObject json = new JSONObject(text);
                    Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (json.getInt("status") == 1) {
                        if (json.getJSONObject("data").getJSONArray("list").length() > 0) {
                            listInfo = GsonUtils.JsonToBean(text, CreditOrderListInfo.class);
                            Message msg = new Message();
                            msg.what = 1;
                            handler.sendMessage(msg);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
                creditOrderListView.onRefreshComplete();
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
